package handlers

import (
	"github.com/gin-gonic/gin"
	"news-hub/models"
	"strconv"
)

// Add 新闻添加
func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}

	news := models.News{
		Title:   title,
		Content: content,
	}
	er := models.DB.Create(&news).Debug().Error
	if er != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size

	var news []models.News
	models.DB.Offset(offset).Limit(size).Find(&news)
	var total int64
	models.DB.Model(&news).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "OK",
		"data":  news,
		"total": total,
	})
	return
}
